package com.moyuwanjia.Dao.Impl;

import com.moyuwanjia.Dao.IAccountDao;
import com.moyuwanjia.entity.Account02;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 摸鱼丸加~
 * @create 2022-04-24 14:38
 * 将当前的类交由spring来管理
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Resource
    private QueryRunner queryRunner;

    public List<Account02> findAll() {
        try {
            return queryRunner.query("select * from account02",
                    new BeanListHandler<Account02>(Account02.class));
        }catch (Exception exception){
            throw new RuntimeException(exception);
        }
    }

    public Account02 findAccountById(Integer id) {
        try {
            return queryRunner.query("select * from account02 where id = ?",new BeanHandler<Account02>(Account02.class),id);
        }catch (Exception exception){
             throw new RuntimeException(exception);
        }
    }

    public Integer saveAccount(Account02 account02) {
        try {
            return queryRunner.update("insert into account02(name,money) values(?,?)",account02.getName(),account02.getMoney());
        } catch (SQLException sqlException) {
            throw  new RuntimeException(sqlException);
        }
    }

    public Integer updateAccount(Account02 account02) {
        try {
            return queryRunner.update("update account02 set name= ?,money=? where id = ?",account02.getName(),account02.getMoney(),account02.getId());
        } catch (SQLException sqlException) {
            throw new RuntimeException(sqlException);
        }
    }

    public Integer deleteAccountById(Integer id) {
        try {
            return queryRunner.update("delete from account02 where id = ?",id);
        } catch (SQLException sqlException) {
            throw new RuntimeException(sqlException);
        }
    }
}
